package cc.c3p0.admin.config.servlet;

import cc.c3p0.admin.common.filter.AuthorizationFilter;
import cc.c3p0.admin.common.resolver.CurrentUserMethodArgumentResolver;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * web mvc 配置
 * Created by binchao on 2017/5/10.
 */
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Resource
    private CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver;

    @Value("${auth.urls.urlPatterns}")
    private String patterns;

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(currentUserMethodArgumentResolver);
    }

    @Bean
    public FilterRegistrationBean getAuthorizationFilter() {
        AuthorizationFilter authorizationFilter = new AuthorizationFilter();
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(authorizationFilter);
        List<String> urlPatterns = new ArrayList<>();
        for (String s : patterns.split(",")) {
            urlPatterns.add(s);
        }
        registrationBean.setUrlPatterns(urlPatterns);
        registrationBean.setOrder(1);
        return registrationBean;
    }
}
